var EventProxy = require('eventproxy');
var User = require('../proxy').User;
var Relation = require('../proxy').Relation;
var Card = require('../proxy').Card;
var Activity = require('../proxy').Activity;
var redisManager = require('../proxy').RedisManager;
var FactionMember = require('../proxy').FactionMember;
var logger = require('../service/Logger');

exports.saveUser = function(req, res, next){
    var name = 'lgy',
        gender = '男',
        headimg = 'logo.jpg';
    User.newAndSave(name, gender, headimg, function(err, data){
        console.log(err)
        console.log(data)
        res.send('save ok~')
    });
}
/**
 *
 * @param req
 * @param res
 * @param next
 */
exports.getUser = function(req, res, next){
    var id = req.params.id,
        me = req.params.currentUser,
        factionId = req.params.factionId;
    if(!id || id === me.id){
        User.getUserById(me.id, function(err, user){
            if(err){ logger.error(err.message);return res.render('others/error',{error:err})}
            FactionMember.getFactionMembersByUserId(me.id, function(err, fms){
                if(err){ logger.error(e.message);return res.render('others/error',{error:err})}
                var fmArr = [];
                fms.forEach(function(fm){
                    if(!fm.faction.isDelete){
                        fmArr.push(fm)
                    }
                });
                res.render('user/user', {user: user, card: user.card, id: me.id, fms: fmArr, isFriend: true});
            })
        });
    }else{
        redisManager.isInUserSet(me.id, id, function(err, isIn){
            var isFriend = false;
            if(isIn == 1){
                isFriend = true;
            }
            if(factionId){
                _getUserInfoInFaction(id, me, factionId, function(user, tag, card){
                    res.render('user/user', {user: user, tag: tag, card: card, id: me.id, isFriend: isFriend});
                });
            }else{
                _getUserInfoInCircle(id, me, function(user, tag, card){
                    res.render('user/user', {user: user, tag:tag, card: card, id: me.id, isFriend: isFriend});
                })
            }
        })
    }
}

function _getUserInfoInCircle(id, me, callback){
    _getUserAndRelation(id, me, function(err, user, rel){
        var tag = rel ? rel.tag : null;
        var permission = user.permission,
            card = user.card;
        if(permission){
            Card.setCardColumePermission(permission, card, function(card){
                callback(user, tag, card);
            })
        }else{
            callback(user, tag, card);
        }
    })
}
function _getUserInfoInFaction(id, me, factionId, callback){
    _getUserAndRelation(id, me, function(err, user, rel){
        var tag = rel ? rel.tag : null;
        var card = user.card;
        FactionMember.getFactionPermission(id, factionId, function(err, permission){
            if(id !== me.id && permission){
                Card.setCardColumePermission(permission, card, function(card){
                    callback(user, tag, card);
                });
            }else{
                callback(user, tag, card);
            }
        })
    })
}
function _getUserAndRelation(id, me, callback){
    var ep = new EventProxy();
    ep.bind('error', function(err){
        if(err) logger.debug(err.message);
        ep.unbind();
        callback(err);
        //res.render('others/error', {error: err.message})
    })
    ep.all('getUser', 'getRelation', function(user, rel){
        callback(null, user, rel);
    })
    User.getUserById(id, function(err, user){
        if(err){ ep.emit('error', err); }
        ep.emit('getUser', user);
    });
    Relation.findRelByUseroneAndTwo(me.id, id, function(err, rel){
        if(err){ ep.emit('error', err); }
        ep.emit('getRelation', rel);
    });
}
/**
 *
 * @param req
 * @param res
 * @param next
 */
exports.completeInfo = function(req, res, next){
    var mobile = req.body.mobile,
        company = req.body.company,
        business = req.body.business;
    var me = req.params.currentUser;
    User.getUserById(me.id, function(err, user){
        if(err){ logger.error(e.message);res.send({error:err})}
        var card = user.card;
        if(mobile)
            card.mobile = mobile;
        if(company)
            card.company = company;
        if(business)
            card.business = business;
        Card.updateCard(card._id, card, function(err, card){
            if(err){ logger.error(e.message);res.send({error:err})}
            res.send({data: card});
        });
    })
}
/**
 *
 * @param req
 * @param res
 * @param next
 */
exports.addTag = function(req, res, next){
    var targetId = req.body.userId,
        tag = req.body.tag,
        me = req.params.currentUser;
    Relation.findRelAndAddTag(me.id, targetId, tag, function(err, data){
        if(err) return res.send({error: err.message});
        if(!data){
            return res.send({data: 'none'})
        }
        return res.send({data: {tag: tag}});
    });
}
/**
 *
 * @param req
 * @param res
 * @param next
 */
exports.removeTag = function(req, res, next){
    var targetId = req.body.userId,
        tag = req.body.tag,
        me = req.params.currentUser;
    Relation.findRelAndRemoveTag(me.id, targetId, tag, function(err, data){
        if(err) return res.send({error: err.message});
        res.send({data: {tag: tag}})
    })
}
/**
 *
 * @param req
 * @param res
 * @param next
 */
exports.newCard = function(req, res, next){
    var me = req.params.currentUser;
    var cardId = req.params.cardId;
    if(cardId){
        Card.findCardById(cardId, function(err, card){
            res.render('user/new_card', {user:me, card:card})
        })
    }else{
        res.render('user/new_card', {user:me, card:null});
    }
}
/**
 *
 * @param req
 * @param res
 * @param next
 */
exports.editUser = function(req, res, next){
    var me = req.params.currentUser;
    var forwardUrl = req.params.forwardUrl;
    User.getUserById(me.id, function(err, user){
        res.render('user/new_card', {user:me, card:user.card, forwardUrl:forwardUrl })
    })
}

/**
 *
 * @param req
 * @param res
 * @param next
 */
exports.saveCard = function(req, res, next){
    var cardId = req.body.cardId;
    var name = req.body.name,
        company = req.body.company,
        position = req.body.position,
        mobile = req.body.mobile,
        email = req.body.email,
        business = req.body.business,
        address = req.body.address,
        product = req.body.product;
    var me = req.params.currentUser;
    var refererUrl = req.headers.referer;
    var forward = null
    if(/tofaction_/.test(refererUrl)){
        forward = '/faction/'+refererUrl.substring(refererUrl.match(/tofaction_/).index+10);
    }
    if(cardId){
        var newCardInfo = {
            name: name,
            company: company,
            position: position,
            mobile: mobile,
            email: email,
            business: business,
            address: address,
            product: product
        }
        Card.updateCard(cardId, newCardInfo, function(err, resp){
            if(err) return res.send({error: err.message});
            //更新faction_members的member信息
            FactionMember.updateFactionsMembersInfo(me.id, newCardInfo, function(err, data){
                if(err) logger.error(err);
                logger.debug('User ['+me.id+'] update factionMembers info ok...');
            })
            res.send({data: newCardInfo, forwardUrl: forward});
        })
    }else{
        Card.newAndSave(me, {company: company,
            position: position,
            mobile: mobile,
            email: email,
            business: business,
            address: address}, function(err, card){
            if(err) return res.send({error: err.message});
            User.setDefaultCard(me.id, card, function(err, data){
                if(err) return res.send({error: err.message});
                res.send({data: data, forwardUrl: forward})
            });
        })
    }
}
/**
 *
 * @param req
 * @param res
 * @param next
 */
exports.receiveCard = function(req, res, next){
    var userId = req.body.userId,
        me = req.params.currentUser;
    redisManager.isInUserSet(me.id, userId, function(err, isIn){
        if(isIn == 1){
            return res.send({already: 'already'});
        }
        Relation.addRelationWeight(me.id, userId, 0, function(err, resp){
            if(err) return res.send({error:'失败'})
            res.send({data:resp});
        })
    })
}

exports.setPrivacy = function(req, res, next){
    var me = req.params.currentUser;
    User.getUserById(me.id, function(err, user){
        if(user.permission){
            res.render('user/privacy', {user: user,
                card:user.card,
                permission: user.permission})
        }else{//初始化permission
            user.permission = {
                showMobile: false,
                showCompany: true,
                showPosition: true,
                showEmail: true,
                showBusiness: true,
                showProduct: true
            }
            user.save(function(err, user){
                res.render('user/privacy', {user: user,
                    card:user.card,
                    permission: user.permission})
            })
        }
    })
}
exports.savePrivacy = function(req, res, next){
    var me = req.params.currentUser,
        factionId = req.body.faction,
        flag = req.body.flag === 'true'?true:false,
        colume = req.body.colume;
    if(factionId){
        FactionMember.setPrivacy4User(me.id, factionId, flag, colume, function(err, data){
            if(err){
                logger.error(err.stack);
                return res.send({error:err})
            }
            res.send({data: data})
        })
    }else{
        User.setPrivacy4User(me.id, flag, colume, function(err, data){
            if(err){
                logger.error(err.stack);
                return res.send({error:err})
            }
            res.send({data: data})
        })
    }
}
/**
 *  我的人脉
 * @param req
 * @param res
 * @param next
 */
exports.myCircle = function(req, res, next){
    var me = req.params.currentUser;
    var pageNo = req.params.pageNo?req.params.pageNo: 1,
        pageSize = 10;
    Relation.findRelsByUserone(me.id, pageNo, pageSize, function(err, rels){
        if(err) {logger.error(err.message);res.render('others/error',{error:err})}
        var ep = new EventProxy();
        ep.bind('error', function(err){
            logger.error(err.message);
            ep.unbind();
            res.render('others/error', {error:err});
        })
        ep.after('getUser', rels.length, function(users){
            res.render('user/my_circle', {users: users.sort(_sortWeight),
                pageNo: pageNo+1,
                pageSize:pageSize })
        })
        //TODO: 再处理排序问题
        for(var i= 0,len=rels.length; i<len; i++){
            (function(rel){
                //TODO: redisManager 缓存增加card？
                User.getUserById(rel.usertwo, function(err, user){
                    _buildTagHtml(user, rel.tag, rel.weight ,function(taguser){
                        console.log(taguser)
                        ep.emit('getUser', taguser);
                    });
                })
            })(rels[i])
        }
    })
}

//TODO: fixed: 独立吃一个cluster 处理请求，不要影响master 进程
exports.getRelationInfos = function(req, res, next){
    var me = req.params.currentUser,
        targetUser = req.params.id;
    var ep = new EventProxy();
    ep.all('factions', 'acts', function(factions, acts){
        res.send({factions: factions, acts: acts});
    })
    //共同圈子
    _getTheSameFaction(me.id, targetUser, function(sameFactions){
        ep.emit('factions', sameFactions);
    })
    //共同聚会
    _getTheSameActivity(me.id, targetUser, function(sameActs){
        ep.emit('acts', sameActs);
    })
}
function _getTheSameActivity(userid, targetid, callback){
    var ep = new EventProxy();
    ep.all('me', 'target', function(myacts, targetacts){
        var total = myacts.concat(targetacts),
            tmpmap = {}, sameArr = [];
        for(var i in total){
            if(tmpmap[total[i].id]){
                sameArr.push(total[i]);
            }else{
                tmpmap[total[i].id] = total[i].id;
            }
        }
        //TODO: 适当保存做cache
        callback(sameArr)
    })
    ep.bind('error', function(err){
        logger.error(err); ep.unbind();
        return callback(err);
    })
    Activity.getAllMyActs(userid, function(err, acts){
        if(err) ep.emit('error', err);
        ep.emit('me', acts);
    })
    Activity.getAllMyActs(targetid, function(err, acts){
        if(err) ep.emit('error', err);
        ep.emit('target', acts);
    })
}
function _getTheSameFaction(userid, targetid, callback){
    var ep = new EventProxy();
    ep.all('me', 'target', function(myfactions, targetfactions){
        var total = myfactions.concat(targetfactions),
            tmpmap = {}, sameArr = [];
        //console.log(total)
        for(var i in total){
            if(tmpmap[total[i].id]){
                sameArr.push(total[i]);
            }else{
                tmpmap[total[i].id] = total[i].id;
            }
        }
        //TODO: 适当保存做cache
        callback(sameArr);
    });
    ep.bind('error', function(err){
        logger.error(err);
        ep.unbind();
        return callback(err)
    })
    User.getUserById(userid, function(err, user){
        if(err) ep.emit('error', err);
        ep.emit('me', user.factions);
    })
    User.getUserById(targetid, function(err, user2){
        if(err) ep.emit('error', err);
        ep.emit('target', user2.factions);
    })
}

/**
 * 异步加载user
 * @param req
 * @param res
 * @param next
 */
exports.fetchUsers = function(req, res, next){
    var me = req.params.currentUser,
        pageNo = parseInt(req.body.pageNo),
        pageSize = 10;
    Relation.findRelsByUserone(me.id, pageNo, pageSize, function(err, rels){
        if(err) {logger.error(err.message);res.render('others/error',{error:err})}
        var ep = new EventProxy();
        ep.bind('error', function(err){
            logger.error(err.message);
            ep.unbind();
            res.send({error:'抱歉，出问题了'});
        })
        ep.after('getUser', rels.length, function(users){
            res.send({users: users.sort(_sortWeight),
                pageNo: pageNo+1 })
        })
        //TODO: 再处理排序问题
        for(var i= 0,len=rels.length; i<len; i++){
            (function(rel){
                //TODO: redisManager 缓存增加card？
                User.getUserById(rel.usertwo, function(err, user){
                    _buildTagHtml(user, rel.tag, rel.weight ,function(taguser){
                        ep.emit('getUser', taguser);
                    });
                })
            })(rels[i])
        }
    })
}
function _sortWeight(a, b){
    return b.weight - a.weight;
}
//TODO: 重写此方法
function _buildTagHtml(user, tags, weight, callback){
    var result = {};
    var html = '';
    for(var i= 0,len=tags.length; i< len; i++){
        if(tags[i] === '我的死党'){
            html += '<span class="label label-danger">'+tags[i]+'</span> ';
        }else
        if(tags[i] === '好朋友'){
            html += '<span class="label label-warning">'+tags[i]+'</span> ';
        }else{
            html += '<span class="label label-primary">'+tags[i]+'</span> ';
        }

    }
    result.id = user.id;
    result.name= user.card.name,
        result.position= user.card.position,
        result.company= user.card.company,
        result.weight= weight,
        //result.level= user.level,// 暂无
        //result.score= user.score,// 暂无
        result.tags = html;
    callback(result)

}